﻿using System;
using System.Diagnostics;
using System.Resources;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using VoiceControl.Models;
using System.Xml.Linq;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using Coding4Fun.Toolkit.Controls;
using System.Windows.Media;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace VoiceControl
{
    public partial class App : Application
    {

        public static ObservableCollection<FileInfo> FileData = new ObservableCollection<FileInfo>();

        public static ObservableCollection<String> FileNames = new ObservableCollection<string>();

        public static ObservableCollection<string> EmailFile = new ObservableCollection<string>();

        public static BasicSetting Setting = new BasicSetting();

        public static Dictionary<String, String> Search = new Dictionary<string, string>();
        public static Dictionary<String, String> Office = new Dictionary<string, string>();
        public static Dictionary<String, String> Web = new Dictionary<string, string>();
        public static Dictionary<String, String> WinCommand = new Dictionary<string, string>();

        public static List<string> SearchList = new List<string>();
        public static List<string> OfficeList = new List<string>();
        public static List<string> WebList = new List<string>();
        public static List<string> WinCommandList = new List<string>();

        /// <summary>
        ///提供对电话应用程序的根框架的轻松访问。
        /// </summary>
        /// <returns>电话应用程序的根框架。</returns>
        public static PhoneApplicationFrame RootFrame { get; private set; }

        /// <summary>
        /// Application 对象的构造函数。
        /// </summary>
        public App()
        {
            // 未捕获的异常的全局处理程序。
            UnhandledException += Application_UnhandledException;

            // 标准 XAML 初始化
            InitializeComponent();

            // 特定于电话的初始化
            InitializePhoneApplication();

            // 调试时显示图形分析信息。
            if (Debugger.IsAttached)
            {
                // 显示当前帧速率计数器。
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // 显示在每个帧中重绘的应用程序区域。
                //Application.Current.Host.Settings.EnableRedrawRegions = true；

                // 启用非生产分析可视化模式，
                // 该模式显示递交给 GPU 的包含彩色重叠区的页面区域。
                //Application.Current.Host.Settings.EnableCacheVisualization = true；

                // 通过禁用以下对象阻止在调试过程中关闭屏幕
                // 应用程序的空闲检测。
                //  注意: 仅在调试模式下使用此设置。禁用用户空闲检测的应用程序在用户不使用电话时将继续运行
                // 并且消耗电池电量。
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }

        }

        // 应用程序启动(例如，从“开始”菜单启动)时执行的代码
        // 此代码在重新激活应用程序时不执行
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            LoadSetting();
            LoadDict();
        }

        // 激活应用程序(置于前台)时执行的代码
        // 此代码在首次启动应用程序时不执行
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
        }

        // 停用应用程序(发送到后台)时执行的代码
        // 此代码在应用程序关闭时不执行
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
        }

        // 应用程序关闭(例如，用户点击“后退”)时执行的代码
        // 此代码在停用应用程序时不执行
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
        }

        // 导航失败时执行的代码
        private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // 导航已失败；强行进入调试器
                Debugger.Break();
            }
        }

        // 出现未处理的异常时执行的代码
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // 出现未处理的异常；强行进入调试器
                Debugger.Break();
            }
        }

        #region 电话应用程序初始化

        // 避免双重初始化
        private bool phoneApplicationInitialized = false;

        // 请勿向此方法中添加任何其他代码
        private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;

            // 创建框架但先不将它设置为 RootVisual；这允许初始
            // 屏幕保持活动状态，直到准备呈现应用程序时。
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // 处理导航故障
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // 在下一次导航中处理清除 BackStack 的重置请求，
            RootFrame.Navigated += CheckForResetNavigation;

            // 确保我们未再次初始化
            phoneApplicationInitialized = true;
        }

        // 请勿向此方法中添加任何其他代码
        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
            // 设置根视觉效果以允许应用程序呈现
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;

            // 删除此处理程序，因为不再需要它
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

        private void CheckForResetNavigation(object sender, NavigationEventArgs e)
        {
            // 如果应用程序收到“重置”导航，则需要进行检查
            // 以确定是否应重置页面堆栈
            if (e.NavigationMode == NavigationMode.Reset)
                RootFrame.Navigated += ClearBackStackAfterReset;
        }

        private void ClearBackStackAfterReset(object sender, NavigationEventArgs e)
        {
            // 取消注册事件，以便不再调用该事件
            RootFrame.Navigated -= ClearBackStackAfterReset;

            // 只为“新建”(向前)和“刷新”导航清除堆栈
            if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh)
                return;

            // 为了获得 UI 一致性，请清除整个页面堆栈
            while (RootFrame.RemoveBackEntry() != null)
            {
                ; // 不执行任何操作
            }
        }

        #endregion

        /// <summary>
        /// 用于提示
        /// </summary>
        public class ToastTips : ToastPrompt
        {
            /// <summary>
            /// 显示顶部的Toast通知
            /// </summary>
            /// <param name="message">通知的内容</param>
            public ToastTips(string message)
            {
                Thickness a = new Thickness(0, 25, 0, 0);
                this.Title = message;
                this.Margin = a;
                //this.Background = new SolidColorBrush(Color.FromArgb(255, 0, 133, 226));
                this.Foreground = new SolidColorBrush(Colors.White);
                this.Message = " ";
                this.FontSize = 28;
                this.Height = 72;
                this.Show();
            }
        }

        async void LoadSetting()
        {
            try
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.Async = true;
                FileStream fs = File.OpenRead("Setting.xml");
                using (XmlReader reader = XmlReader.Create(fs, settings))
                {
                    while (await reader.ReadAsync())
                    {
                        if (reader.Name == "Server")
                        {
                            App.Setting.ServerIP = reader.GetAttribute("IP");
                            App.Setting.Port = reader.GetAttribute("Port");
                        }
                    }
                }
            }
            catch
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("配置读取失败！");
                        return;
                    });
            }
        }

        async void LoadDict()
        {
            try
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.Async = true;
                FileStream fs = File.OpenRead("VoiceGrammar/Dict.xml");
                XDocument loadedData = XDocument.Load("VoiceGrammar/Dict.xml");
                using (XmlReader reader = XmlReader.Create(fs, settings))
                {
                    while (await reader.ReadAsync())
                    {
                        if(reader.Name=="SearchSite")
                        {
                            Search.Add(reader.GetAttribute("Name"), reader.GetAttribute("EnName"));
                            SearchList.Add(reader.GetAttribute("Name"));
                        }
                        if (reader.Name == "OfficeProgram")
                        {
                            Office.Add(reader.GetAttribute("Text"), reader.GetAttribute("Operation"));
                            OfficeList.Add(reader.GetAttribute("Text"));
                        }
                        if (reader.Name == "WebSite")
                        {
                            Web.Add(reader.GetAttribute("Text"), reader.GetAttribute("Operation"));
                            WebList.Add(reader.GetAttribute("Text"));
                        }
                        if (reader.Name == "Cmd")
                        {
                            WinCommand.Add(reader.GetAttribute("Text"), reader.GetAttribute("Operation"));
                            WinCommandList.Add(reader.GetAttribute("Text"));
                        }
                    }
                }
                
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }
    }
}